﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using InternalManagementSystem.DAO.Models;
using System.Configuration;
using System.Web.Configuration;

public partial class Companys_Index : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            PermissionHelper hh = new PermissionHelper();
            //Permission p = hh.GetPermission(EUserRole.admin);//支持扣分
            //p.UserID = 9;

            //Permission p = hh.GetPermission(EUserRole.leader);//新建违章信息
            //p.UserID = 10;


            //Permission p = hh.GetPermission(EUserRole.superadmin);//超级管理员 编辑删除违章信息
            //p.UserID = 7;
          
            //Session["Permission"] = p;
            btnCreate.Visible = false;
            setLeader.Visible = false;
            btnImport.Visible = false;
            fuImport.Visible = false;

            if (Session["Permission"] != null)
            {
                Permission permission = Session["Permission"] as Permission;
                if (permission.IsCompanyEdit)
                {
                    btnCreate.Visible = true;
                     
                }

                if (permission.IsDoAssign)
                {

                    setLeader.Visible = true;
                }

                if (permission.IsCompanyEdit && permission.IsUserEdit)
                {
                    btnImport.Visible = true;
                    fuImport.Visible = true;
                }

                Bind(permission);


            }
        }
    }

    void Bind(Permission permission)
    {
        CompanyBLL cbll = new CompanyBLL(permission);
        switch (permission.EUserRole)
        {
            case EUserRole.superadmin:
                gvCompanys.Columns[12].Visible = true;
                gvCompanys.Columns[0].Visible = true;
                 gvCompanys.DataSource = cbll.GetAllCompany();
                 gvCompanys.DataBind();
                break;
            case EUserRole.admin:
                gvCompanys.Columns[12].Visible = false;
                gvCompanys.Columns[0].Visible = false;
                gvCompanys.DataSource = cbll.GetAllCompany();
                gvCompanys.DataBind();
                break;
            case EUserRole.leader:
                gvCompanys.Columns[12].Visible = false;
                gvCompanys.Columns[0].Visible = false;
                gvCompanys.DataSource = cbll.GetCompanyAssigned(permission.UserID);
                gvCompanys.DataBind();
                break;
            default:
                 gvCompanys.Columns[12].Visible = false;
                gvCompanys.Columns[0].Visible = false;
                break;

        }
      
        

        UserBLL ubll = new UserBLL(permission);
        ddlleader.DataSource = ubll.GetLeaderRoleUser();
        ddlleader.DataTextField = "UserName";
        ddlleader.DataValueField = "UserID";
        ddlleader.DataBind();

    }

    protected void gvUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        if (Session["Permission"] != null)
        {
            Permission permission = Session["Permission"] as Permission;
            if (!permission.IsUserEdit)
            {

                return;
            }
            string cid = gvCompanys.DataKeys[e.RowIndex].Value.ToString();//获取主键  

            Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
            string mainCompanyName = config.AppSettings.Settings["maincompany"].Value;

            CompanyBLL cbll = new CompanyBLL(permission);
            cbll.MainCompanyName = mainCompanyName;
            cbll.DeleteCompany(Convert.ToInt32(cid));

            Response.Write("<script> alert( '删除成功！ ');location= 'Index.aspx'</script> ");
        }
    }
    protected void gvCompanys_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (Session["Permission"] != null)
        {
            Permission permission = Session["Permission"] as Permission;

            if (e.CommandName == "Edit" && permission.IsUserEdit)
            {
                string uid = ((HiddenField)gvCompanys.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("hCompanyID")).Value;
                Response.Redirect("Edit.aspx?cid=" + uid);
            }

            if (e.CommandName == "Select")
            {
                 //选中
                //string uid = ((HiddenField)gvCompanys.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("hCompanyID")).Value;
                //Response.Redirect("~/Users/Index.aspx?cid=" + uid);
            }

            if (e.CommandName == "UserList")
            {
                //选中
                Response.Redirect("~/Users/Index.aspx?cid=" + e.CommandArgument);
            } 
        }
    }
    protected void gvCompanys_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        if (Session["Permission"] != null)
        {
            Permission permission = Session["Permission"] as Permission;

            gvCompanys.PageIndex = e.NewPageIndex;
            Bind(permission);
        }
    }
    protected void btnCreate_Click(object sender, EventArgs e)
    {
        Response.Redirect("Create.aspx");
    }
   

    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {
        foreach (GridViewRow row in gvCompanys.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                row.Attributes["onmouseover"] =
                   "currentcolor=this.style.backgroundColor;this.style.backgroundColor='#C0C0FF';this.style.cursor='hand';";
                row.Attributes["onmouseout"] =
                   "this.style.backgroundColor=currentcolor";
                // Set the last parameter to True 
                // to register for event validation. 
                //row.Attributes["onclick"] =
                // ClientScript.GetPostBackClientHyperlink(gvCompanys,
                //    "Select$" + row.DataItemIndex, true);
                if (row.Cells[2].Text == System.Configuration.ConfigurationManager.AppSettings["maincompany"])
                {
                    row.Cells[12].Controls.Clear();
                    row.Cells[0].Controls.Clear();
                }
            }
        }
        base.Render(writer);
    }


    IList<string> GetSelectedRowsKey()
    {
        List<string> result = new List<string>();

        int rowCount = gvCompanys.Rows.Count;

        for (int i = 0; i < rowCount; i++)
        {
            CheckBox tempChk = (CheckBox)gvCompanys.Rows[i].FindControl("CheckItem");
            HiddenField HidID = (HiddenField)gvCompanys.Rows[i].FindControl("hCompanyID");
            if (tempChk.Checked == true)
            {
                result.Add(HidID.Value);
            }
        }

        return result;
    }

    protected void BtnSetLeader_Click(object sender, EventArgs e)
    {
        IList<string> result = GetSelectedRowsKey();
        if (result.Count > 0&&ddlleader.SelectedIndex != -1)
        {
            CompanyBLL cbll = new CompanyBLL();
            int leaderid =  Convert.ToInt32(ddlleader.SelectedValue);
            foreach (string cid in result)
            {
                cbll.DoAssign(Convert.ToInt32(cid), leaderid);
            }
        }
    }
    protected void gvCompanys_RowEditing(object sender, GridViewEditEventArgs e)
    {

    }
    protected void btnImport_Click(object sender, EventArgs e)
    {
        string msg = "", msg4c = "", msg4s = "";
        if (Session["Permission"] != null)
        {
            Permission permission = Session["Permission"] as Permission;

            CompanyBLL cbll = new CompanyBLL(permission);
            UserBLL ubll = new UserBLL(permission);
            AdminBLL abll = new AdminBLL(permission);
            #region 保存
            Boolean fileOK = false;
            String path = Server.MapPath("~/Upload/");
            if (fuImport.HasFile)
            {
                String fileExtension =
                    System.IO.Path.GetExtension(fuImport.FileName).ToLower();
                String[] allowedExtensions = { ".xls", ".xlsx", ".csv" };
                for (int i = 0; i < allowedExtensions.Length; i++)
                {
                    if (fileExtension == allowedExtensions[i])
                    {
                        fileOK = true;
                    }
                }
            }
            else
            {
                msg = "上传文件类型必须为xls,xlsx或csv文件";
            }

            if (fileOK)
            {
                string fullpath = path
                        + fuImport.FileName;
                try
                {
                    fuImport.PostedFile.SaveAs(fullpath);
                    
                }
                catch
                {
                    msg = "上传失败";
                    fileOK = false;
                }

                if (fileOK)
                {
                    //解析excel
                    ExcelHelper helper = new ExcelHelper(fullpath);
                    List<string> sheetNames = helper.GetWorksheetNames();
                    //company sheetNames[0]
                    //公司名	地址	联系方式	联系人	电话	邮箱
                    helper.AddMapping<Company>(o => o.CompanyName, "公司名");
                    helper.AddMapping<Company>(o => o.Address, "地址");
                    helper.AddMapping<Company>(o => o.Contact, "联系方式");
                    helper.AddMapping<Company>(o => o.ContactPerson, "联系人");
                    helper.AddMapping<Company>(o => o.Phone, "电话");
                    helper.AddMapping<Company>(o => o.Email, "邮箱");
                    IList<Company> tCompanyList = helper.Query<Company>(sheetNames[0]);

                    foreach (Company pCompany in tCompanyList)
                    {
                        pCompany.GuardLine = 6;
                        pCompany.CurrentIntegral = 12;
                        if (!cbll.AddCompany(pCompany))
                        {
                            msg4c += pCompany.CompanyName + ",";
                        }
                    }
                    //staff sheetNames[1]
                    //姓名	公司名	性别	工种	证件号	身份证号	员工类别
                    helper.AddMapping<Staff4Excel>(o => o.Name, "姓名");
                    helper.AddMapping<Staff4Excel>(o => o.CompanyName, "公司名");
                    helper.AddMapping<Staff4Excel>(o => o.Sex, "性别");
                    helper.AddMapping<Staff4Excel>(o => o.Worktype, "工种");
                    helper.AddMapping<Staff4Excel>(o => o.Credential, "证件号");
                    helper.AddMapping<Staff4Excel>(o => o.IDCard, "身份证号");
                    helper.AddMapping<Staff4Excel>(o => o.Usertype, "员工类别");

                    List<Company> companyList = cbll.GetAllCompany().ToList();
                    List<UserType> usertypeList = abll.GetAllUserType().ToList();

                    IList<Staff4Excel> tStaff4ExcelList = helper.Query<Staff4Excel>(sheetNames[1]);

                    foreach (Staff4Excel pStaff4Excel in tStaff4ExcelList)
                    {
                        Staff pStaff = pStaff4Excel.ConvertToStaff(companyList, usertypeList);
                        if (pStaff != null)
                        {
                            if (ubll.AddUser(pStaff))
                            {
                                msg4s += pStaff.UserName + ",";
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(msg4c))
                    {
                        msg4c = "重复公司名：" + msg4c.Substring(0, msg4c.Length - 1);
                    }

                    if (!string.IsNullOrEmpty(msg4s))
                    {
                        msg4s = "重复用户名：" + msg4s.Substring(0, msg4s.Length - 1);
                    }
                }
            }

            if (!string.IsNullOrEmpty(msg4c) || !string.IsNullOrEmpty(msg4s))
            {
                msg = msg4c + msg4s;
            }
            else
            {
                msg = "上传成功";
            }

            #endregion

        }
        else
        {
            msg = "没有权限";
        }
        Response.Write("<script> alert( '" + msg + " ');location= 'Index.aspx'</script> ");
       // Response.Redirect("Index.aspx");
    }

    public class Staff4Excel
    {
        public string Name { get; set; }
        public string CompanyName { get; set; }
        public string Sex { get; set; }
        public string Worktype { get; set; }
        public string Credential { get; set; }
        public string IDCard { get; set; }
        public string Usertype { get; set; }

        public Staff ConvertToStaff(List<Company> companyList, List<UserType> usertypeList)
        {
            Staff pStaff = new Staff();
            Company c = companyList.Where(o => o.CompanyName == CompanyName).FirstOrDefault();
            if (c != default(Company))
            {
                pStaff.CompanyID = c.CompanyID;
            }
            else
            {
                return null;
            }

            if (Sex == "男")
                pStaff.Sex = 1;
            else
                pStaff.Sex = 0;

            UserType u = usertypeList.Where(o => o.Name == Usertype).FirstOrDefault();
            if (u != default(UserType))
            {
                pStaff.UserTypeID = u.ID;
            }
            else
            {
                return null;
            }

            pStaff.RoleID = 4;//普通员工
            pStaff.Password = "1234";
            pStaff.CurrentIntegral = 6;

            pStaff.UserName = Name;
            pStaff.WorkType = Worktype;
            pStaff.Credential = Credential;
            pStaff.IDCard = IDCard;


            return pStaff;

        }
    }
}
